package stats

import (
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"ssdevice/common/constant"
	"ssdevice/internal/rule/engine/tools"
	"strings"
	"time"
)

// CalBasicAlgos 计算统计值
func CalBasicAlgos(sn string, col string, tableName string, startTime time.Time, endTime time.Time) map[string]interface{} {
	result := make(map[string]interface{}, 0)
	valueList := []map[string]interface{}{}

	colArr := strings.Split(col, "_")
	var keys string

	if len(colArr) > 1 {
		keys = strings.Join(colArr[0:], "' ->> '")
	} else {
		keys = col
	}

	env.Db.Raw(`SELECT value -> '`+keys+`' AS value FROM "`+tableName+`"
			WHERE
				update_time >= ? 
				AND update_time < ? 
				AND dev_sn = ?
				AND value -> '`+keys+`' is not null
			ORDER BY update_time ASC`, startTime, endTime, sn).Scan(&valueList)

	result[constant.AlgoMax] = nil
	result[constant.AlgoMin] = nil
	result[constant.AlgoSum] = nil
	result[constant.AlgoAverage] = nil
	result[constant.AlgoStart] = nil
	result[constant.AlgoEnd] = nil
	result[constant.AlgoDiff] = nil

	var max1, min1, sum, start, end, avg, diff float64
	var num = 0.0

	for _, vMap := range valueList {
		vStr, _ := vMap["value"]
		vNum, err := tools.StringToFloat(vStr.(string))
		if err != nil {
			continue
		}

		num++
		if num != 0 {
			if vNum > max1 {
				max1 = vNum
			}

			//最小
			if vNum < min1 {
				min1 = vNum
			}
		} else {
			max1 = vNum
			min1 = vNum
		}

		// 开始和结束
		end = vNum
		if num == 1 {
			start = vNum
		}

		//求和
		sum += vNum
	}

	// 平均
	avg = sum / num
	//差值
	diff = end - start

	if num != 0 {
		result[constant.AlgoMax] = max1
		result[constant.AlgoMin] = min1
		result[constant.AlgoSum] = sum
		result[constant.AlgoAverage] = avg
		result[constant.AlgoStart] = start
		result[constant.AlgoEnd] = end
		result[constant.AlgoDiff] = diff
	}

	return result
}
